import os, urllib
from rer import kwargs, Categories, SampleData, getModelMaxIndex
#from google.appengine.api import users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class CreateSampleData(webapp.RequestHandler):
    @kwargs
    def post(self, pattern, title, description, category):
        if not title or not pattern or not description or not category:
            prm = []
            if pattern:
                prm.append('pattern=' + urllib.quote(pattern))
            
            if title:
                prm.append('title=' + urllib.quote(title))
            
            if description:
                prm.append('description=' + urllib.quote(description))
            
            if category:
                prm.append('category=' + urllib.quote(category))
            
            self.redirect('/create_sampledata' + (('?' + '&'.join(prm)) if prm.length else ''))
        
        
        c = db.get(db.Key(category))
        if c is None:
            self.redirect('/reference')
        
        data = SampleData(index       = getModelMaxIndex(SampleData) + 1,
                          category    = c,
                          pattern     = db.Text( pattern if pattern != '' else '-' ),
                          title       = db.Text( title if title != '' else '-' ),
                          description = db.Text( description if description != '' else '-' ))      
        data.put()
        
        params = ('?cr=' + urllib.quote(c.en)) if c else ''
        self.redirect('/reference' + params)
        return

    @kwargs
    def get(self, pattern, title, description, category, msg):
        categories = Categories.all()
        data = SampleData(index       = 9999,
                          category    = db.get(db.Key(category)) if category != '' else categories.get(),
                          pattern     = db.Text( pattern if pattern != '' else '-' ),
                          title       = db.Text( title if title != '' else '-' ),
                          description = db.Text( description if description != '' else '-' ))
        
        res = {'sub_title' : 'Create SampleData',
               'categories': categories,
               'msg'       : msg,
               'data'      : data}
        path = os.path.join(os.path.dirname(__file__), 'template', 'create.sampledata.html')
        self.response.out.write(template.render(path, res))


application = webapp.WSGIApplication([('/create_sampledata', CreateSampleData)], debug=False)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()